package zhou.chs.p3_1;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView tv;  //声明1个TextView，显示文件信息
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.idtv);
        verifyStoragePermissions(this);
    }
    //向文件写入字符串
    public void saveStr(View view){
        String str = "内置存储文件路径：" + this.getFilesDir().toString();
        FileService.saveFile(this,"demo.txt", str);
        str = "扩展存储文件路径：" + getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).toString();
        FileService.saveFileEx(this,"demo.txt", str);
        str = "公共存储文件路径：" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
        FileService.saveFileSD(this,"demo.txt", str);
    }
    //打开文件，获取文件内容并显示
    public void openStr(View view){
        String str = FileService.readFile(this,"demo.txt");
        str += "\n\n" + FileService.readFileEx(this,"demo.txt");
        str += "\n\n" + FileService.readFileSD(this,"demo.txt");
        tv.setText(str);
    }
    //动态申请存储卡的读写权限
    public static void verifyStoragePermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }
}
